#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QFontDatabase>
#include <QFont>
#include <QQuickView>
#include <QQuickItem>
#include <QtQuickWidgets/QQuickWidget>
#include <QtWidgets/QWidget>
#include "viewer.h"
#include "paintitem.h"
#include "process.h"
#include <QApplication>

RosConnector *connector=nullptr;

// 设置字体
void setFont(const QString& fontUrl)
{
    int fontId = QFontDatabase::addApplicationFont(fontUrl);
    QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);

    QFont font;
    if (fontFamilies.size() > 0)
    {
        font.setFamily(fontFamilies.at(0));
        //font.setPixelSize(14);
    }
    QApplication::setFont(font);
}

int initEngine(QApplication& app, QQmlApplicationEngine& engine)
{
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine,
                     &QQmlApplicationEngine::objectCreated,
                     &app,
                     [url](QObject *obj, const QUrl &objUrl)
                     {
                         if (!obj && url == objUrl) QCoreApplication::exit(-1);
                     },
                     Qt::QueuedConnection
    );
    engine.load(url);

    if (engine.rootObjects().isEmpty())
        return -1;
    return 0;
}

// 封装函数举例
int func(int a, int b)
{
    return a + b;
}
class A
{
public:
    int func(int a, int b)
    {
        return c + a + b;
    }
    int c = 1;
};
void bindFunction()
{
    int a = 1, b = 2;
    std::function<int()> func1 = [a, b](){
      return func(a, b);
    };
    A aa;
    std::function<int()> func2 = [&aa, a, b](){
      return aa.func(a, b);
    };
}



int main(int argc, char *argv[])
{    
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    qmlRegisterType<PaintItem>("PaintItemModule",1,0,"PaintItem");
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;

    setFont("qrc:/fonts/simhei.ttf");
    initEngine(app, engine);

    // 初始化界面控制器Viewer
    Viewer* view = initViewer(engine);

    // 初始化上下文
    context* curContext = new context(1, 0, S1);

    ros::init(argc, argv, "rosconnector");
    ros::NodeHandle nh;

    connector=new RosConnector(nh,view);

    // 切换自动\手动模式
    while(!curContext->isEnd()){
        processInAutoMode(view, curContext);
        if(curContext->isEnd()) break;
        processInManualMode(view, curContext);
    }

    return app.exec();
}
